using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Collections;
using HyperVSnapin.Object;
using System.Management;

namespace HyperVSnapin.Command
{
    [Cmdlet(VerbsCommon.Get, "VM", SupportsShouldProcess = true)]
    public class GetVMCommand : Cmdlet
    {
        private Host[] host;

        #region Parameters
        [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the Virtual Machine to retrieve")]
        [ValidateNotNullOrEmpty]
        public string[] Name
        {
            get;
            set;
        }

        [Parameter(Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Help Text")]
        public Host[] VHost
        {
            get
            {
                if (this.host == null)
                {
                    return new Host[] {HyperVSnapin.Object.Host.StaticHost};
                }
                else
                {
                    return host;
                }
            }
            set
            {
                this.host = value;
            }
        }

        #endregion

        protected override void ProcessRecord()
        {
            try
            {
                Helpers.VirtualMachineWMIHelper helper = new HyperVSnapin.Helpers.VirtualMachineWMIHelper();
                List<VirtualMachine> results = new List<VirtualMachine>();
                foreach (Host currentHost in this.VHost)
                {
                    foreach (string vmName in this.Name) 
                    {
                        List<ManagementObject> mos = helper.GetVirtualMachines(vmName, currentHost.ConnectionAddress, currentHost.ConnectionCredential);
                        foreach (ManagementObject mo in mos)
                        {
                            results.Add(new VirtualMachine(mo, currentHost));
                        }
                    }
                }
                WriteObject(results, true);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "GetHyperVServerCommand" + ex, ErrorCategory.NotSpecified, null));
            }
        }
    }
}
